package tk.mybatis.springboot.model;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class TestThread extends ReentrantLock {
    long time;

    public TestThread() {
        this.time = 0;
    }

    @Override
    public void lock() {
        super.lock();
        log.info("================================== TestThread lock start ======================");
        time = System.currentTimeMillis();
    }

    @Override
    public void unlock() {
        super.unlock();
        log.info("================================== TestThread lock exec time :{}", (System.currentTimeMillis() - time) / 1000);
    }

    public void checkError() {
        if (flagErrorMethod1 || flagErrorMethod2) {
            throw new RuntimeException("发生异常了 线程id :{}" + Thread.currentThread().getId()
                    + "- flagErrorMethod1 :" + flagErrorMethod1
                    + "-  flagErrorMethod2 :" + flagErrorMethod2);
        }
    }

    public boolean allSuccess() {
        if (flagSuccessMethod1 && flagSuccessMethod2) {
            return true;
        }
        checkError();
        return false;
    }


    private volatile boolean flagErrorMethod1 = false;
    private volatile boolean flagErrorMethod2 = false;

    private volatile boolean flagSuccessMethod1 = false;
    private volatile boolean flagSuccessMethod2 = false;

    public void setFlagErrorMethod1() {
        this.flagErrorMethod1 = true;
        checkError();
    }

    public void setFlagErrorMethod2() {
        this.flagErrorMethod2 = true;
        checkError();
    }

    public void setFlagSuccessMethod1() {
        this.flagSuccessMethod1 = true;
    }

    public void setFlagSuccessMethod2() {
        this.flagSuccessMethod2 = true;
    }
}
